/**
 * Copyright(c): 2017 com.mjduan All rights reserved.
 * 项目名：learn-spring-web
 * 注意：未经作者允许，不得外传
 */
package com.mjduan.project.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author dmj1161859184@126.com 2018-08-19 04:10
 * @version 1.0
 * @since 1.0
 */
public class HttpsessionFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpsessionFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("session filter doFilter()");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String contextPath = httpServletRequest.getContextPath();
        String servletPath = httpServletRequest.getServletPath();
        LOGGER.info("contextPath:{},servletPath:{}", contextPath, servletPath);
        if ("/login.jsp".equals(servletPath)) {
            LOGGER.info("创建session");
            httpServletRequest.getSession(true);
            chain.doFilter(request, response);
        } else if ((httpServletRequest.getSession(false) == null)) {
            LOGGER.info("从request中获得的session为null，跳转到session timeout界面");
            request.getRequestDispatcher("/resources/views/jsp/sessionTimeout.jsp").forward(request, response);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
